previous_unread_count = -1;
setInterval("checkNewMsg()",10000);

function checkNewMsg(){
	cookie=getCookie();
	if(!nullOrEmpty(cookie)){
	  $.cookie("reddit_session",cookie);
	  updateBadge();
	}
	else{
      pokki.removeIconBadge();
      tryLogin();
	}
}

function updateBadge(){
  $.get(unread_msg_url,function(data){
			if(data!=""){
        unread_count = data.data.children.length;
        if(previous_unread_count != unread_count){
            previous_unread_count = unread_count;
            if(nullOrEmpty(localStorage.getItem("first_time"))){
                localStorage.setItem("need_to_refresh","yeah");
            }
            else{
                localStorage.removeItem("first_time");
            }
        }
        if(unread_count == 0){
          pokki.removeIconBadge();
        }
        else{
          pokki.setIconBadge(unread_count);
        }
			}
		});
}

function tryLogin(){
  user = localStorage.getItem("user");
  password = getPassword();

  if(!nullOrEmpty(user) && !nullOrEmpty(password)){
    doLogin(user,password,function(){});
  }
}

function doLogin(user, password) {
  $.post(login_url + "/" + user, {user: user, passwd: password, api_type: "json"}, function(data) {
      if (data.json.errors.length == 0) {
        $.cookie("reddit_session", data.json.data.cookie);
        saveCookie(data.json.data.cookie);
        saveModHash(data.json.data.modhash);
        localStorage.setItem("user", user);
        savePassword(password);
      }
    });
}